<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
             :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">

        <el-col :span="12" class="mb20">
          <el-form-item label="设备采集数据外键ID" prop="devDataId">
            <el-input v-model="form.devDataId" placeholder="请输入设备采集数据外键ID（预留）"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="设备ID" prop="devId">
            <el-input v-model="form.devId" placeholder="请输入设备ID"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="消息特定信息" prop="messageSpecialInfo">
            <el-input v-model="form.messageSpecialInfo" placeholder="请输入消息特定信息" />
            <div v-if="form.messageSpecialInfo" class="mt8">
              <el-image :src="thisPageState.imgBaseUrl + getImageUrl(form)"
                        :fit="'contain'" style="max-width: 200px;">
              </el-image>
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="消息类型" prop="messageType">
            <el-input v-model="form.messageType" placeholder="请输入消息类型 BINGCHONG_ALARM BEST_ALARM"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="消息描述" prop="messageDescribe">
            <el-input v-model="form.messageDescribe" placeholder="请输入消息描述"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="消息特定信息" prop="messageSpecialInfo">
            <el-input v-model="form.messageSpecialInfo" placeholder="请输入消息特定信息"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="消息状态" prop="messageStatement">
            <el-input v-model="form.messageStatement" placeholder="请输入消息状态"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="创建人" prop="createBy">
            <el-input v-model="form.createBy" placeholder="请输入创建人"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="上传时间" prop="createTime">
            <el-input v-model="form.createTime" placeholder="请输入上传时间"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="修改人" prop="updateBy">
            <el-input v-model="form.updateBy" placeholder="请输入修改人"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="更新时间" prop="updateTime">
            <el-input v-model="form.updateTime" placeholder="请输入更新时间"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="删除标志" prop="delFlag">
            <el-input v-model="form.delFlag" placeholder="请输入删除标志"/>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="IotDeviceMessageDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/iot/iotDeviceMessage'
import { rule } from '/@/utils/validate';
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典

// 提交表单数据
const form = reactive({
  id:'',
  devDataId: '',
  devId: '',
  messageType: '',
  messageDescribe: '',
  messageSpecialInfo: '',
  messageStatement: '',
  createBy: '',
  createTime: '',
  updateBy: '',
  updateTime: '',
  delFlag: '',
});

// 定义校验规则
const dataRules = ref({
})

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true;
  form.id = '';

  // 获取iotDeviceMessage信息
  if (id) {
    form.id = id;
    getiotDeviceMessageData(id).finally(() => {
      nextTick(() => {
        dataFormRef.value?.resetFields();
      });
    });
  } else {
    nextTick(() => {
      dataFormRef.value?.resetFields();
    });
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getiotDeviceMessageData = (id: string) => {
  loading.value = true;
  getObj(id)
      .then((res: any) => {
        console.log('接口返回数据:', res.data); // 打印接口返回数据
        Object.assign(form, res.data);
      })
      .finally(() => {
        loading.value = false;
      });
};
const thisPageState = reactive({
  imgBaseUrl: import.meta.env.VITE_API_URL,
});

// 新增方法
const getImageUrl = (item) => {
  const match = item.messageSpecialInfo.match(/url=([^}]+)/);
  return match ? match[1] : '';
};// 暴露变量
defineExpose({
  openDialog
});
</script>